package com.axin.auth.service;

import cn.hutool.core.util.ObjectUtil;
import com.axin.common.core.exception.ServiceException;
import com.axin.common.security.model.LoginUser;
import com.axin.common.core.domain.web.AjaxResult;
import com.axin.system.api.RemotePermissionService;
import com.axin.system.api.RemoteUserService;
import com.axin.system.api.domain.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * 用户验证处理
 *
 * @Author axin
 * @Date 2021/9/11 21:47
 **/
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private RemoteUserService userService;

    @Autowired
    private RemotePermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        AjaxResult<SysUser> result = userService.selectUserByUserName(username);
        if(!result.isSuccess()) {
            throw new ServiceException(result.getMsg());
        }
        if (ObjectUtil.isNull(result.getData())) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("登录用户：" + username + " 不存在");
        }

        return createLoginUser(result.getData());
    }

    public UserDetails createLoginUser(SysUser user) {
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            perms.add("*:*:*");
        } else {
            AjaxResult<Set<String>> result = permissionService.getMenuPermission(user.getUserId());
            if(!result.isSuccess()) {
                throw new ServiceException(result.getMsg());
            }
            perms = result.getData();
        }

        return new LoginUser(user.getUserId(), user, perms);
    }
}
